package nia.chapter2.echoserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.net.ProtocolException;

/**
 * 代码清单 2-2 EchoServer 类
 *
 * @author <a href="mailto:norman.maurer@gmail.com">Norman Maurer</a>
 */
public class EchoServer {
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        //消息处理器
        final EchoServerHandler serverHandler = new EchoServerHandler();
        //(1) 创建EventLoopGroup,它是一个线程池，Executor-》ExecutorService
        EventLoopGroup executor = new NioEventLoopGroup();
 /*       EventLoopGroup boss = new NioEventLoopGroup();
        EventLoopGroup worker = new NioEventLoopGroup();*/
        //(2) 创建ServerBootstrap
        ServerBootstrap b = new ServerBootstrap();
        try {
            //(3)设置线程池，一个boss一个worker
            b.group(executor)
                    //(4) 指定所使用的NIO传输Channel
                    .channel(NioServerSocketChannel.class)
                    //(5) 使用指定的端口设置套接字地址
                    .localAddress(new InetSocketAddress(port))
                    //(5) 添加一个EchoServerHandler到于Channel的 ChannelPipeline
                    //ChannelPipelise相当于一个过滤器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //EchoServerHandler 被标注为@Shareable，所以我们可以总是使用同样的实例
                            //这里对于所有的客户端连接来说，都会使用同一个 EchoServerHandler，因为其被标注为@Sharable，
                            //这将在后面的章节中讲到。
                            //ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(serverHandler);
                        }
                    });

            //(6) 异步地绑定服务器；调用 sync()方法阻塞等待直到绑定完成
            //sysnc()方法相当于selector.select()方法，阻塞等待连接。
            ChannelFuture f = b.bind().sync();

            System.out.println(EchoServer.class.getName() +
                    " started and listening for connections on " + f.channel().localAddress());
            //(7) 获取 Channel 的CloseFuture，并且阻塞当前线程直到它完成
            f.channel().closeFuture().sync();
        } finally {
            //(8) 关闭 EventLoopGroup，释放所有的资源
            executor.shutdownGracefully().sync();
        }
    }
}
